import logging

import requests

from Util.DBUtil import DBUtil
from Util.request_token_util import upm_token_server
from sqlalchemy import text

#手工执行人群接口
service_url = 'https://www.cdp.changan.com.cn/audience/api/segment/{}/execute'

querySql = ("SELECT DISTINCT t.segment_id FROM audience_data_service.segment_task t WHERE "
            " (STATUS = 1 AND current_exec_status = 301 AND (create_datetime >= DATE_FORMAT( CURRENT_TIME (),'%Y/%m/%d' ) "
            " OR ( next_update_datetime IS NOT NULL AND next_update_datetime >= DATE_FORMAT( CURRENT_TIME (),'%Y/%m/%d' ) )))")


class SegmentService:
    def __init__(self, db_url):
        self.db_url = db_url

    def segment_error_list(self):
        db_self = DBUtil(self.db_url)
        logging.info(querySql)
        results = db_self.execute_query(text(querySql))
        url_list = []  # 创建一个空列表来存储替换后的URL
        if results:
            for row in results:
                segment_id = row[0]  # 获取第一个元素，即 id 列的值
                url = service_url.format(segment_id)  # 使用 format() 方法将 segment_id 插入到 URL 中
                url_list.append(url)  # 将替换后的 URL 添加到列表中
                logging.info(f"Tag ID: {segment_id}, URL: {url}")
        return url_list  # 返回包含所有替换后的 URL 的列表

    def segment_execute(self, urls):
        if not urls:
            logging.info("URL list is empty")
            return
        upm_token = upm_token_server.get_upm_token()
        if not upm_token:
            print("token获取失败")
        else:
            head_map = upm_token.get_head_map()
            cookie_map = upm_token.get_cookie_map()
            for url in urls:
                response = requests.put(url, headers=head_map, cookies=cookie_map, json={})
                insert_api_log(self, "segment_execute", url, response, "", ""),
                print(f"HTTP Response: {response.status_code} {response.text}")


def insert_api_log(self, api_name, request_params, response_result, execution_status, error_message):
    db_util = DBUtil(self.db_url)
    query = text("""
    INSERT INTO api_execution_log (api_name, request_params, response_result, execution_status, error_message)
    VALUES (:api_name, :request_params, :response_result, :execution_status, :error_message)
    """)

    params = {
        'api_name': api_name,
        'request_params': request_params,
        'response_result': response_result,
        'execution_status': execution_status,
        'error_message': error_message
    }

    db_util.execute_update(query, params)
    print("记录插入成功")


# 运行主函数
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    segment_service = SegmentService(
        "mysql+pymysql://root:d1o0N1z!rbELRf3r@rm-2vc9b10eck3rpbbv7.mysql.cn-chengdu.rds.aliyuncs.com:3306/object_modeling_v2")
    urls = segment_service.segment_error_list()
    logging.info(f"All URLs: {urls}")
    segment_service.segment_execute(urls)
